package com.yuke.cloud.service.omc.controller.frontend;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.omc.dto.OrderProdDto;
import com.yuke.cloud.service.omc.entity.OdsOrder;
import com.yuke.cloud.service.omc.entity.OdsOrderGoods;
import com.yuke.cloud.service.omc.service.OdsOrderGoodsService;
import com.yuke.cloud.service.omc.service.OdsOrderService;
import com.yuke.cloud.service.omc.service.OdsTeamIntentService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/mall/ods/order")
public class MallController {
    @Resource
    private OdsOrderGoodsService odsOrderGoodsService;
    @Resource
    private OdsTeamIntentService odsTeamIntentService;
    @Resource
    private OdsOrderService odsOrderService;

    // add by wg 20190727
    @Value("${yuke.shop-rebate-rate}")
    private Double shopRebateRate;

    @RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
    public String test(@PathVariable String id) {
        return id;
    }

    //统计本月的销售量
    //todo 两次循环性能降低
    @RequestMapping(value = "/countnumberbymonth", method = RequestMethod.POST)
    public Wrapper countnumberbymonth(@RequestBody JSONObject jsonObject) {
        Object products = jsonObject.get("products");
        List<OdsOrderGoods> list = new ArrayList<OdsOrderGoods>();
        List<Map> products1 = (List<Map>) products;
        for (int i = 0; i < products1.size(); i++) {
            Long shopid = Long.valueOf(products1.get(i).get("shopid").toString());
            Long specid = Long.valueOf(products1.get(i).get("specid").toString());
            OdsOrderGoods odsOrderGoods1 = new OdsOrderGoods();
            odsOrderGoods1.setOrderId(shopid);
            odsOrderGoods1.setSpecId(specid);
            list.add(odsOrderGoods1);
        }
        //获取某个店铺的总销售量
        // mod by wg 20190802
        if (list != null && list.size() > 0) {
            List<Map> shoptotal = odsOrderGoodsService.selectnumbyshopidmonth(list);
            if (shoptotal.size() == 0) {
                List<Map<String, String>> end1 = new ArrayList<Map<String, String>>();
                for (int i = 0; i < products1.size(); i++) {
                    Map<String, String> map1 = new HashMap();
                    map1.put("shopId", products1.get(i).get("shopid").toString());
                    map1.put("specId", products1.get(i).get("specid").toString());
                    map1.put("totalnums", "0");
                    map1.put("goodsnum", "0");
                    end1.add(map1);
                }
                String s = JSON.toJSONString(end1);
                return WrapMapper.ok(s);
            }
            //获取某件个店铺某个商品的销量
            List<Map> specidtotal = odsOrderGoodsService.getcountnumbyshopandbyspecid(list);
            List<Map<String, String>> lis = new ArrayList();
            for (int i = 0; i < specidtotal.size(); i++) {
                Map<String, String> map = new HashMap<String, String>();
                for (int j = 0; j < shoptotal.size(); j++) {
                    if (shoptotal.get(j).get("shop_id").toString().equals(specidtotal.get(i).get("shop_id").toString())) {
                        map.put("shopid", shoptotal.get(j).get("shop_id").toString());
                        map.put("goodsnum", specidtotal.get(i).get("goods_num").toString());
                        map.put("totalnums", shoptotal.get(j).get("num").toString());
                        map.put("specid", specidtotal.get(i).get("spec_id").toString());
                        lis.add(map);
                    }
                }
            }

            List<Map<String, String>> end = new ArrayList<Map<String, String>>();
            for (int i = 0; i < products1.size(); i++) {
                Map<String, String> map = new HashMap();
                map.put("shopId", products1.get(i).get("shopid").toString());
                map.put("specId", products1.get(i).get("specid").toString());
                boolean flag1 = true;
                boolean flag2 = true;
                for (int j = 0; j < lis.size(); j++) {
                    if (products1.get(i).get("shopid").toString().equals(lis.get(j).get("shopid"))) {
                        map.put("totalnums", lis.get(j).get("totalnums"));
                        flag1 = false;
                        if (products1.get(i).get("specid").toString().equals(lis.get(j).get("specid"))) {
                            map.put("goodsnum", lis.get(j).get("goodsnum"));
                            flag2 = false;
                        }
                    }
                }
                if (flag1) {
                    map.put("totalnums", "0");
                    map.put("goodsnum", "0");
                }
                if (flag2) {
                    map.put("goodsnum", "0");
                }
                end.add(map);
            }
            String s = JSON.toJSONString(end);
            return WrapMapper.ok(s);
        } else {
            return WrapMapper.error("参数错误，未传入商品");
        }
    }

    @GetMapping(value = "/getShopRebateRate")
    @ApiOperation(httpMethod = "GET", value = "获取店铺订货返利率")
    public Wrapper<Double> getShopRebateRate() {
        return WrapMapper.ok(shopRebateRate);
    }

    @PostMapping(value = "/gettest")
    public Map<String, List<OrderProdDto>> doIt(List<OrderProdDto> orderProdDto) {
        //对结果集进行分组求和
        Map<String, List<OrderProdDto>> resultMap = orderProdDto.stream().collect(Collectors.groupingBy(OrderProdDto::getShopName
        ));
        List<OrderProdDto> result = new ArrayList<>();
        OrderProdDto aaa = new OrderProdDto();
        resultMap.forEach((k, kList) -> {

            IntSummaryStatistics nmap = kList.stream().collect(Collectors.summarizingInt(e->Integer.valueOf(e.getPurchasePrice().toString())));

            aaa.setShopId(kList.get(0).getShopId());
            aaa.setProductPriceTotal(Integer.valueOf(nmap.toString()));
            result.add(aaa);

        });

        return resultMap;
    }

    /**
     * 查看当前团长信息
     * @param userId
     * @return
     */
    @GetMapping("/app/{userId}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper countTeamIntentNumber(@ApiParam(name = "userId", value = "记录id") @PathVariable Long userId) {

        //统计有多少人在该团长处下过单
        Integer number = odsTeamIntentService.countTeamIntentNumber(userId);

        return WrapMapper.ok(number);
    }

    // 获取用户订单数（不包括已取消及无效作废的）
    @GetMapping("/getUserOrderCount/{userId}")
    public Wrapper getUserOrderCount(@PathVariable Long userId) {
        int count = 0;
        Example example = new Example(OdsOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        criteria.andNotEqualTo("orderStatus", 3); // 已取消
        criteria.andNotEqualTo("orderStatus", 6); // 已作废
        count = odsOrderService.selectCountByExample(example);
        return WrapMapper.ok(count);
    }
}
